package org.edu.modules.stu.zhsz.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.edu.common.dto.ExcelPo;
import org.edu.common.system.vo.LoginUser;
import org.edu.common.util.oConvertUtils;
import org.edu.common.utils.PoiUtils;
import org.edu.modules.stu.base.dto.VeBaseStudentDto;
import org.edu.modules.stu.base.service.VeBaseStudentService;
import org.edu.modules.stu.common.entity.VeBaseAppUser;
import org.edu.modules.stu.common.entity.VeBaseBanji;
import org.edu.modules.stu.common.entity.VeBaseTeacher;
import org.edu.modules.stu.common.service.VeBaseAppUserService;
import org.edu.modules.stu.common.service.VeBaseBanjiService;
import org.edu.modules.stu.common.service.VeBaseTeacherService;
import org.edu.modules.stu.zhsz.dto.VeStuMoralActiveDto;
import org.edu.common.dto.AllDto;
import org.edu.modules.stu.zhsz.entity.VeStuMoralActive;
import org.edu.modules.stu.zhsz.entity.VeStuMoralProgram;
import org.edu.modules.stu.zhsz.service.VeStuMoralActiveService;
import org.edu.common.api.vo.Result;
import org.edu.common.base.PageDto;
import org.edu.common.dto.StatusDto;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.query.QueryGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Api(tags = {"德育活动表"})
@RestController
@RequestMapping("/stu/veStuMoralActive")
@Slf4j
public class VeStuMoralActiveController {

    @Autowired
    private VeStuMoralActiveService veStuMoralActiveService;

    @Autowired
    private VeBaseAppUserService veBaseAppUserService;

    @Autowired
    private VeBaseStudentService veBaseStudentService;

    @Autowired
    private VeBaseTeacherService veBaseTeacherService;

    @Autowired
    private VeBaseBanjiService veBaseBanjiService;

    @ApiOperation("分页查询德育活动表")
    @PostMapping("/page")
    public Result<?> page(@RequestBody PageDto<VeStuMoralActive> page) {
        QueryWrapper<VeStuMoralActive> queryWrapper = page.buildQueryWrapper(VeStuMoralActive.class);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //根据用户id查用户信息
        VeBaseAppUser appUser = veBaseAppUserService.getVeBaseAppUserById(sysUser.getId());
        if (appUser.getUserType().contains("1")) {
            //根据工号查教师信息
            VeBaseTeacher baseTeacher = veBaseTeacherService.getByUserId(appUser.getUserId());
            if (page.getParams() != null && page.getParams().containsKey("my")) {
                //查询 包含全校和班级
                queryWrapper.apply("status=1 and is_all =1");
                //查班级
                /*List<VeBaseBanji> banjis = veBaseBanjiService.listByTeacherId(baseTeacher.getId());
                StringBuilder bjids = new StringBuilder();
                for (VeBaseBanji baseBanji : banjis) {
                    if (baseBanji.getId() != null) { // 过滤空值
                        bjids.append(baseBanji.getId()).append(",");  // 添加分隔符
                    }
                }
                // 去除末尾多余的分隔符
                String result = bjids.length() > 0 ? bjids.deleteCharAt(bjids.length() - 1).toString() : "";
                queryWrapper.apply(" status=1 and is_all =1 or id in(select mc_id from ve_stu_moral_active_user where bj_id in ({0})) ",
                        result);*/
            } else {
                //管理自己发布的
                queryWrapper.apply(" push_user={0} ",
                        appUser.getUserId());
            }

        } else if (appUser.getUserType().contains("2")) {
            //根据学号查学生信息
            VeBaseStudentDto baseStudent = veBaseStudentService.findDtoByXh(appUser.getUserId());
            if (page.getParams() != null && page.getParams().containsKey("my")) {
                queryWrapper.apply(" (status=1 and is_all =1 or id in( select mc_id from ve_stu_moral_active_user where user_id={0} ) ) ",
                        baseStudent.getId());
            }
        }
        return Result.OK(veStuMoralActiveService.page(page, queryWrapper));
    }

    /**
     * 查询所有
     */
    @ApiOperation("查询所有")
    @PostMapping("/all")
    public Result<?> all(@RequestBody AllDto<VeStuMoralActive> page) {
        QueryWrapper<VeStuMoralActive> queryWrapper = page.buildQueryWrapper(VeStuMoralActive.class);
        List<VeStuMoralActive> list = veStuMoralActiveService.listByWrapper(queryWrapper);
        return Result.OK(list);
    }

    @ApiOperation("导出数据）")
    @PostMapping("/export")
    public Result<?> export(@RequestBody PageDto<VeStuMoralActive> page, HttpServletResponse resp) {
        QueryWrapper<VeStuMoralActive> queryWrapper = page.buildQueryWrapper(VeStuMoralActive.class);
        List<ExcelPo> list = new ArrayList<>();
        list.add(new ExcelPo("活动类型（0：班级，1：校级）", "type"));
        list.add(new ExcelPo("活动标题", "title"));
        list.add(new ExcelPo("活动内容", "content"));
        list.add(new ExcelPo("状态（0：未发布，1：发布）", "status"));
        list.add(new ExcelPo("发布时间", "pushtime"));
        list.add(new ExcelPo("开始时间", "starttime"));
        list.add(new ExcelPo("结束时间", "endtime"));
        list.add(new ExcelPo("创建用户", "createuser"));
        list.add(new ExcelPo("发布的人", "pushuser"));
        list.add(new ExcelPo("是否全班或全校（0：否，1：是）", "isall"));
        list.add(new ExcelPo("终端Id", "terminalid"));
        PoiUtils.downloadFile(resp, veStuMoralActiveService.page(page, queryWrapper).getRecords(), list);
        return Result.OK();
    }

    @AutoLog(value = "德育活动表-分页列表查询")
    @ApiOperation(value = "德育活动表-分页列表查询", notes = "德育活动表-分页列表查询")
    @PostMapping(value = "/list")
    public Result<?> queryPageList(VeStuMoralActive entity,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<VeStuMoralActive> queryWrapper = QueryGenerator.initQueryWrapper(entity, req.getParameterMap());
        PageDto<VeStuMoralActive> page = new PageDto<VeStuMoralActive>(pageNo, pageSize);
        IPage<VeStuMoralActive> pageList = veStuMoralActiveService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


    @AutoLog(value = "通过id查询")
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        VeStuMoralActive dto = veStuMoralActiveService.findDtoById(id);
        if (dto == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(dto);
    }

    @AutoLog(value = "添加")
    @ApiOperation(value = "添加", notes = "添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody VeStuMoralActiveDto dto) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (oConvertUtils.isEmpty(loginUser)) {
            return Result.error("请登录系统！");
        }
        //根据用户id查用户信息
        VeBaseAppUser appUser = veBaseAppUserService.getVeBaseAppUserById(loginUser.getId());
        dto.setPushUser(appUser.getUserId());
        dto.setPushUserName(appUser.getRealName());
        veStuMoralActiveService.insertOrUpdate(dto, true);
        return Result.OK("添加成功！");
    }

    @AutoLog(value = "编辑")
    @ApiOperation(value = "编辑", notes = "编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody VeStuMoralActiveDto dto) {
        veStuMoralActiveService.insertOrUpdate(dto, false);
        return Result.OK("编辑成功!");
    }

    @AutoLog(value = "批量删除")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        veStuMoralActiveService.delete(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }


    @AutoLog(value = "更新状态")
    @ApiOperation(value = "更新状态")
    @PostMapping(value = "/updateStatus")
    public Result<?> updateStatus(@RequestBody StatusDto statusDto) {
        LambdaUpdateWrapper<VeStuMoralActive> updateWrapper = new LambdaUpdateWrapper<>();
        if (statusDto.getIds() != null && statusDto.getIds().size() > 0) {
            updateWrapper.set(VeStuMoralActive::getStatus, statusDto.getStatus());

            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            updateWrapper.set(VeStuMoralActive::getPushTime, new Date());
            updateWrapper.set(VeStuMoralActive::getPushUser, sysUser.getId());
            updateWrapper.set(VeStuMoralActive::getPushUserName, sysUser.getRealname());


            updateWrapper.in(VeStuMoralActive::getId, statusDto.getIds());
            veStuMoralActiveService.update(updateWrapper);
            return Result.OK("批量更新成功!");
        } else {
            return Result.error("未选择!");
        }
    }


}
